package com.wqd.search.service.impl;

import com.wqd.model.common.dtos.ResponseResult;
import com.wqd.model.common.enums.AppHttpCodeEnum;
import com.wqd.model.search.dtos.HistorySearchDto;
import com.wqd.model.user.pojos.ApUser;
import com.wqd.search.pojos.ApUserSearch;
import com.wqd.search.service.ApUserSearchService;
import com.wqd.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存历史记录
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        if(keyword == null || keyword.equals("")){
            return;
        }
        //查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        //从mongodb中查询到该数据转换成apUserSearch实体类
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearch != null) {
            //如果查到就更新查询时间
            apUserSearch.setCreatedTime(new Date());
            //保存
            mongoTemplate.save(apUserSearch);
            return;
        }
        //不存在该数据,先判断总记录是否超过10,超过10就删掉最久的
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        //要求查询到的数据是当前用户的
        query = Query.query(Criteria.where("userId").is(userId));
        //要求查询降序排序
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        //得到搜索集合
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);

        //查询到的结果小于10
        if (apUserSearchList.size() < 10) {
            //直接插入
            mongoTemplate.save(apUserSearch);
        } else {
            //获取最后一条数据(第十条数据)
            ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            //替换数据
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())), apUserSearch);
        }
    }

    /**
     * 查询用户搜索历史
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        ApUser user = ApThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据用户查询数据,并按时间降序排序
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createTime")), ApUserSearch.class);
        //返回结果集
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 删除用户选定的历史记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = ApThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //删除记录
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
